/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.nifi.processors.huawei.credentials.provider.service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.obs.services.IObsCredentialsProvider;
import org.apache.nifi.annotation.behavior.Restricted;
import org.apache.nifi.annotation.behavior.Restriction;
import org.apache.nifi.annotation.documentation.CapabilityDescription;
import org.apache.nifi.annotation.documentation.Tags;
import org.apache.nifi.annotation.lifecycle.OnEnabled;
import org.apache.nifi.components.PropertyDescriptor;
import org.apache.nifi.components.RequiredPermission;
import org.apache.nifi.components.ValidationContext;
import org.apache.nifi.components.ValidationResult;
import org.apache.nifi.controller.AbstractControllerService;
import org.apache.nifi.controller.ConfigurationContext;
import org.apache.nifi.processor.exception.ProcessException;
import org.apache.nifi.processors.huawei.credentials.provider.factory.CredentialsProviderFactory;

import static org.apache.nifi.processors.huawei.common.PropertyDescriptors.ACCESS_KEY;
import static org.apache.nifi.processors.huawei.common.PropertyDescriptors.SECRET_KEY;


/**
 * Implementation of HuaweiCredentialsProviderService interface
 *
 * @see HuaweiCredentialsProviderService
 */
@CapabilityDescription("Defines credentials for Huawei Web Services processors. " +
        "Uses default credentials without configuration. " +
        "Default credentials support ECS instance profile/role, default user profile, environment variables, etc. " +
        "Additional options include access key / secret key pairs, credentials file, named profile, and assume role credentials.")
@Tags({ "huawei", "credentials","provider" })
@Restricted(
        restrictions = {
                @Restriction(
                        requiredPermission = RequiredPermission.ACCESS_ENVIRONMENT_CREDENTIALS,
                        explanation = "The default configuration can read environment variables and system properties for credentials"
                )
        }
)
public class HuaweiCredentialsProviderControllerService extends AbstractControllerService implements HuaweiCredentialsProviderService {
    private volatile IObsCredentialsProvider credentialsProvider;
    protected final CredentialsProviderFactory credentialsProviderFactory = new CredentialsProviderFactory();

    @Override
    protected List<PropertyDescriptor> getSupportedPropertyDescriptors() {
        final List<PropertyDescriptor> props = new ArrayList<>();
        props.add(ACCESS_KEY);
        props.add(SECRET_KEY);
        return Collections.unmodifiableList(props);
    }

    @Override
    public IObsCredentialsProvider getCredentialsProvider() throws ProcessException {
        return credentialsProvider;
    }

    @Override
    protected Collection<ValidationResult> customValidate(final ValidationContext validationContext) {
        return credentialsProviderFactory.validate(validationContext);
    }

    @OnEnabled
    public void onConfigured(final ConfigurationContext context) {
        final Map<PropertyDescriptor, String> evaluatedProperties = new HashMap<>(context.getProperties());
        evaluatedProperties.keySet().forEach(propertyDescriptor -> {
            if (propertyDescriptor.isExpressionLanguageSupported()) {
                evaluatedProperties.put(propertyDescriptor,
                        context.getProperty(propertyDescriptor).evaluateAttributeExpressions().getValue());
            }
        });
        credentialsProvider = credentialsProviderFactory.getCredentialsProvider(evaluatedProperties);
        getLogger().debug("Using credentials provider: " + credentialsProvider.getClass());
    }

    @Override
    public String toString() {
        return "HuaweiCredentialsProviderService[id=" + getIdentifier() + "]";
    }
}